<?php
declare (strict_types=1);

namespace upload;

/**
 * 图片压缩类：通过缩放来压缩。
 * 如果要保持源图比例，把参数$percent保持为1即可。
 * 即使原比例压缩，也可大幅度缩小。数码相机4M图片。也可以缩为700KB左右。如果缩小比例，则体积会更小。
 *
 * 结果：可保存、可直接显示。
 */
class ImgCompress
{

    private string $src;//提供图片名（可不带扩展名，用源图扩展名）用于保存。或不提供文件名直接显示
    private array $imageinfo;
    private int $new_width;
    private int $new_height;
    private $image;
    private $percent; //如果压缩比为1000时，不进行压缩

    /**
     * 图片压缩
     * ImgCompress constructor.
     * @param string $src
     * @param int $new_width
     * @param int $new_height
     * @param $percent
     */
    public function __construct(string $src, int $new_width, int $new_height, $percent = 0)
    {
        $this->src = $src;
        $this->new_width = $new_width;
        $this->new_height = $new_height;
        $this->percent = $percent;
    }

    /**
     * 高清压缩图片
     * @return array
     */
    public function compressImg(): array
    {
        //内部：打开图片
        $this->_openImage();
        //如果压缩比为1000时，不进行压缩
        if ($this->percent === 1000) {
            return ['src' => $this->src, 'width' => $this->imageinfo['width'], 'height' => $this->imageinfo['height']];
        }
        //内部：操作图片
        $this->_thumpImage();

        if (!empty($this->src)) {
            $this->_saveImage($this->src); //保存
        } else {
            $this->_showImage();
        }
        return ['src' => $this->src, 'width' => $this->new_width, 'height' => $this->new_height];
    }

    /**
     * 内部：打开图片
     */
    private function _openImage()
    {
        list($width, $height, $type, $attr) = getimagesize($this->src);
        $this->imageinfo = array(
            'width' => $width,
            'height' => $height,
            'type' => image_type_to_extension($type, false),
            'attr' => $attr
        );
        $fun = "imagecreatefrom" . $this->imageinfo['type'];
        $this->image = $fun($this->src);
    }

    /**
     * 内部：操作图片
     */
    private function _thumpImage()
    {
        if ($this->percent !== 0) {
            $this->new_width = intval($this->imageinfo['width'] * $this->percent);
            $this->new_height = intval($this->imageinfo['height'] * $this->percent);
            //不指定大小缩放比例，图片最大800*600
            if ($this->new_width > 800) {
                $this->new_height = intval((800 / $this->new_width) * $this->new_height);
                $this->new_width = 800;
            }
            if ($this->new_height > 600) {
                $this->new_width = intval((800 / $this->new_height) * $this->new_width);
                $this->new_height = 600;
            }
        }
        //执行图片处理
        $image_thump = imagecreatetruecolor($this->new_width, $this->new_height);
        //将原图复制带图片载体上面，并且按照一定比例压缩,极大的保持了清晰度
        imagecopyresampled($image_thump, $this->image, 0, 0, 0, 0, $this->new_width, $this->new_height, $this->imageinfo['width'], $this->imageinfo['height']);
        imagedestroy($this->image);
        $this->image = $image_thump;
    }

    /**
     * 输出图片:保存图片则用saveImage()
     */
    private function _showImage()
    {
        header('Content-Type: image/' . $this->imageinfo['type']);
        $funcs = "image" . $this->imageinfo['type'];
        $funcs($this->image);
    }

    /**
     * 保存图片到硬盘：
     * @param string $dstImgName 1、可指定字符串不带后缀的名称，使用源图扩展名 。2、直接指定目标图片名带扩展名。
     */
    private function _saveImage(string $dstImgName)
    {
        if (empty($dstImgName)) return false;
        //如果目标图片名有后缀就用目标图片扩展名 后缀，如果没有，则用源图的扩展名
        $allowImgs = ['.jpg', '.jpeg', '.png', '.bmp', '.wbmp', '.gif'];
        $dstExt = strrchr($dstImgName, ".");
        $sourseExt = strrchr($this->src, ".");
        if (!empty($dstExt)) $dstExt = strtolower($dstExt);
        if (!empty($sourseExt)) $sourseExt = strtolower($sourseExt);
        //有指定目标名扩展名
        if (!empty($dstExt) && in_array($dstExt, $allowImgs)) {
            $dstName = $dstImgName;
        } elseif (!empty($sourseExt) && in_array($sourseExt, $allowImgs)) {
            $dstName = $dstImgName . $sourseExt;
        } else {
            $dstName = $dstImgName . $this->imageinfo['type'];
        }
        $funcs = "image" . $this->imageinfo['type'];
        $funcs($this->image, $dstName);
    }

    /**
     * 销毁图片
     */
    public function __destruct()
    {
        imagedestroy($this->image);
    }
}
